package com.programming.forum.controller;

import com.programming.forum.common.AppResult;
import com.programming.forum.common.ResultCode;
import com.programming.forum.config.AppConfig;
import com.programming.forum.exception.ApplicationException;
import com.programming.forum.model.Article;
import com.programming.forum.model.Board;
import com.programming.forum.model.User;
import com.programming.forum.services.impl.ArticleServiceImpl;
import com.programming.forum.services.impl.BoardServiceImpl;
import com.sun.istack.internal.NotNull;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 22479
 * Date: 2023-11-07
 * Time: 22:15
 */
@Api(tags = "文章接口")
@RequestMapping("/article")
@RestController
@Slf4j
public class ArticleController {

    @Resource
    private BoardServiceImpl boardService;
    @Resource
    private ArticleServiceImpl articleService;

    /**
     * 发布新帖子
     * @param boardId 版块Id
     * @param title 标题
     * @param content 文章内容
     * @return
     */
    @ApiOperation("发布帖子API")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("版块Id") @RequestParam("boardId")  @NotNull Long boardId,
                            @ApiParam("标题") @RequestParam("title") @NotNull String title,
                            @ApiParam("文章内容") @RequestParam("content") @NotNull String content) {
        //检验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if(user.getState() == 1) {
            //用户已禁言 FAILED_USER_BANNED      (1103,"您已被禁言, 请联系管理员, 并重新登录."),
            return AppResult.failed(ResultCode.FAILED_USER_BANNED );
        }
        //版块校验
        Board board = boardService.selectById(boardId);
        if(board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            //版块不存在 或 版块已被删除 或 版块已隐藏
            //FAILED_BOARD_BANNED      (1203,"版块状况异常, 请联系管理员."),
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());

            throw new  ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_BANNED));
        }
        //封装文章对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        //调用service层方法
        articleService.create(article);
        return  AppResult.success("发布文章成功");
    }

    @ApiOperation("获取帖子列表")
    @GetMapping("/getAllByBoardId")
    public AppResult getAllByBoardId(@ApiParam("版块Id") @RequestParam(value = "boardId", required = false) Long boardId) {
        List<Article> articles = null;
        //非空校验
        if(boardId == null) {
            articles = articleService.selectAll();
        } else {
            //校验板块是否存
            Board board = boardService.selectById(boardId);

            articles = articleService.selectByBoardId(boardId);
        }
        //结果是否为空 -- 用于校正标准json
        if(articles == null) {
            articles = new ArrayList<>();
        }
        //响应结果
        return AppResult.success(articles);
    }

    @ApiOperation("根据帖子Id获取详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
            @ApiParam("帖子Id") @RequestParam("id")  @NotNull Long id) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //调用service层
        Article article = articleService.selectDetailById(id);

        if(article == null) {
            //FAILED_NOT_EXISTS        (1005, "资源不存在"),
           return AppResult.failed(ResultCode.FAILED_NOT_EXISTS );
        }

        //判断是否是作者
        if(article.getUserId().equals(user.getId())) {
            //标识为作者
            article.setOwn(true);
        }

        return AppResult.success(article);
    }

    @PostMapping("/modify")
    @ApiOperation(("修改帖子"))
    public AppResult modify(HttpServletRequest request,
                            @ApiParam("文章id") @RequestParam("id") @NotNull Long id,
                            @ApiParam("文章标题") @RequestParam("title") @NotNull String title,
                            @ApiParam("文章正文") @RequestParam("content") @NotNull String content) {

        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //校验用户状态
        if(user.getState() == 1) {
            //用户已禁言 FAILED_USER_BANNED      (1103,"您已被禁言, 请联系管理员, 并重新登录."),
            return AppResult.failed(ResultCode.FAILED_USER_BANNED );
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        //校验帖子是否存在
        if(article == null) {
            //FAILED_NOT_EXISTS        (1005, "资源不存在"),
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS );
        }
        //校验是否是作者
        if(!user.getId().equals(article.getUserId()) ) {
            // FAILED_FORBIDDEN        (1003, "禁止访问"),
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN );
        }
        //校验帖子状态 --是否结帖
        if(article.getState() == 1) {
            // FAILED_Article_BANNED      (1302,"帖子状态异常"),
            return AppResult.failed(ResultCode.FAILED_Article_BANNED);
        }
        //调用dao层
        articleService.modify(id,title,content);
        log.info("更新帖子成功" + "Article id = " + article.getId() + "User id =" + user.getId());
        return AppResult.success();

    }


    @ApiOperation("点赞功能")
    @GetMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
            @ApiParam("文章Id") @RequestParam("id") @NotNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //校验用户状态
        if(user.getState() == 1) {
            //用户已禁言 FAILED_USER_BANNED      (1103,"您已被禁言, 请联系管理员, 并重新登录."),
            return AppResult.failed(ResultCode.FAILED_USER_BANNED );
        }
        //查询帖子详情
        Article article = articleService.selectById(id);

        //校验是否是作者
        if(user.getId().equals(article.getUserId())) {
            // FAILED_Article_thumbsUp_OWN      (1303,"你不能给自己的帖子点赞"),
            return AppResult.failed(ResultCode.FAILED_Article_thumbsUp_OWN );
        }
        articleService.thumbsUpById(id);
        return AppResult.success();

    }


    @ApiOperation("删帖操作")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request,
                            @ApiParam("帖子id") @RequestParam("id") @NotNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);

        //校验用户状态
        if(user.getState() == 1) {
            //用户已禁言 FAILED_USER_BANNED      (1103,"您已被禁言, 请联系管理员, 并重新登录."),
            return AppResult.failed(ResultCode.FAILED_USER_BANNED );
        }
        //查询帖子详情
        Article article = articleService.selectById(id);
        if(article == null || article.getDeleteState() == 1) {
            //帖子不存在
            // 打印日志  FAILED_NOT_EXISTS        (1005, "资源不存在"),
            log.warn(ResultCode. FAILED_NOT_EXISTS .toString());
            // 抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode. FAILED_NOT_EXISTS ));
        }
        //校验是否是作者
        if(!user.getId().equals(article.getUserId())) {
            // FAILED_FORBIDDEN        (1003, "禁止访问"),
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN );
        }
        //调用service
        articleService.deleteById(id);
        return AppResult.success();
    }


    @ApiOperation("获取用户帖子列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId(HttpServletRequest request,
                                    @ApiParam("用户id")
                                     @RequestParam(value = "userId",required = false)   Long userId) {
        //如果userId为空,那么从session中去哦去当前登录用户的Id
        if(userId == null) {
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute(AppConfig.USER_SESSION);
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        if(articles == null) {
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }
}
